package com.leon.collection;

import java.util.Arrays;

public class LeonArrayList {

    private static final int DEFAULT_CAPACITY = 10;

    private Object[] elements;

    private int size;

    public LeonArrayList() {
        elements = new Object[DEFAULT_CAPACITY];
    }

    public LeonArrayList(int capacity) {
        if (capacity > 0) {
            elements = new Object[capacity];
        } else if (capacity == 0) {
            elements = new Object[]{};
        } else {
            throw new IllegalArgumentException("capacity is not allowed to negative");
        }

    }

    public Object get(int index) {
        if (index < 0) {
            throw new IllegalArgumentException("capacity is not allowed to negative");
        }
        if (index > elements.length) {
            throw new IndexOutOfBoundsException();
        }
        return elements[index];
    }

    public void add(Object object) {
        int temp = size + 1;
        if (temp < elements.length) {
            elements[++size] = object;
        } else {
            grow();
            elements[++size] = object;
        }
    }

    public void set(int index, Object object) {
        elements[index] = object;
    }

    public void remove(Object object) {
        if (size == 0) {
            return;
        }
        int target = 0;
        for (int i = 0; i < elements.length; i++) {
            if (elements[i].equals(object)) {
                target = i;
            }
        }
        if (elements.length - target >= 0) {
            System.arraycopy(elements, target + 1, elements, target, elements.length - target);
        }
        size--;
    }

    private void grow() {
        int oldCapacity = elements.length;
        int newCapacity = oldCapacity + oldCapacity >> 1;
        elements = Arrays.copyOf(elements, newCapacity);
    }

}
